<?php

/**
 *  分红计算
 */

namespace app\award;

use app\models\order\Order;
use app\models\user\User;
use app\models\user\UserLevel;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Profit_
{
    // 截断子团队
    private static $split = [];

    // 不是链上的
    private static $chain = [];


    public static function getList($user_id)
    {
        $c = Chain::getChildrenAllQuick($user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4'],
        ], ['id']);
        $c = ArrayHelper::getColumn($c, 'id');

        self::$split = $c;

        $chain = Chain::getReferrerChain($user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4'],
        ]);
        $chain = ArrayHelper::getColumn($chain, 'id');
        $chain = array_merge([$user_id], $chain);

        // var_dump($chain);exit;

        self::$chain = $chain;

        // 从链最顶端开始处理
        $list = self::go($chain[count($chain) - 1]);

        $data = [];
        foreach ($list as $item) {
            // $amount = $item['amount'] - self::sub($list, $item['manager']);
            $amount = $item['amount'] - self::sub_max($list, $item['manager']);
            $data[] = [
                'id' => $item['id'],
                'amount' => $amount > 0 ? $amount : 0
            ];
        }
    }

    protected static function go($user_id, $list = [])
    {

        $query = User::find()
            ->where(['id' => $user_id]);

        $users = $query->andWhere(['level' => [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4']
            ]])
            ->orderBy(['id' => SORT_ASC])
            ->select(['id'])
            ->asArray()
            ->all();

        $users = ArrayHelper::getColumn($users, 'id');

        // var_dump($users);exit;

        // 2) 团队
        $team = [];
        foreach ($users as $user) {
            // 全部
            $children = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip1'],
                UserLevel::$keys['vip2'],
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4'],
            ], ['id']);
            $children = ArrayHelper::getColumn($children, 'id');

            $manager = Chain::getChildrenAllQuick($user, [
                UserLevel::$keys['vip3'],
                UserLevel::$keys['vip4']
            ]);
            $manager = ArrayHelper::getColumn($manager, 'id');

            // 截断处理, 不能是自己的子团队成员
            $manager = array_diff($manager, self::$split);

            // 处理不是链上的
            $diff = array_diff($manager, self::$chain);
            $manager = array_diff($manager, $diff);

            $team[] = [
                'id' => $user,
                'children' => $children,
                'manager' => $manager
            ];
        }

        $users = $team;

        // 3) 业绩
        foreach ($users as $user) {
            $orders = Order::find()
                ->where(['user_id' => array_merge([$user['id']], $user['children'])])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                // 本月
                // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                // 上个月的 (线上要用上个月的)
                // ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                ->all();

            $sum = 0;
            foreach ($orders as $order) {
                $sum += $order['total_quantity'];
            }

            $user['quantity'] = $sum;
            $user['amount'] = self::getAmount($sum);

            if (!key_exists($user['id'], $list)) {
                $list[$user['id']] = $user;
            }

            // 子团队业务
            foreach ($user['manager'] as $item) {
                $list = self::go($item, $list);
            }
        }

        return $list;
    }

    protected static function getAmount($quantity)
    {
        $model = ZSetting::find()
            ->where(['<=', 'start', $quantity])
            ->andWhere(['>=', 'end', $quantity])
            ->one();

        // echo $model->createCommand()->getRawSql();exit;

        if ($model) {
            return $model->amount;
        }

        return 0;
    }

    // 减去最大的
    public static function sub_max($users, $children)
    {
        // 找出需要的团队
        $list = [];
        foreach ($users as $key => $user) {
            if (in_array($key, $children)) {
                array_push($list, $user);
            }
        }

        $max = 0;
        if (!empty($list)) {
            foreach ($list as $item) {
                if ($item['amount'] > $max) {
                    $max = $item['amount'];
                }
            }
        }
        return $max;
    }

    // 需要减掉团队下面全部佣金
    public static function sub($users, $children)
    {
        // 找出需要的团队
        $list = [];
        foreach ($users as $key => $user) {
            if (in_array($key, $children)) {
                array_push($list, $user);
            }
        }

        $sum = 0;
        foreach ($list as $item) {
            $sum += $item['amount'];
        }
        return $sum;
    }
}